import { RuntimeError } from "@ibiz-template/core";
import { resource } from "../global-util/global-util";

/**
 * js工具类
 *
 * @export
 * @class JSUtil
 */
export class JSUtil {

  /**
   * 动态加载静态资源
   *
   * @static
   * @param {string} url
   * @return {*}  {Promise<unknown>}
   * @memberof JSUtil
   */
  private static loadScript(url: string): Promise<unknown> {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = url;
      script.onload = resolve;
      script.onerror = reject;
      document.head.appendChild(script);
    });
  }

  /**
   * 加载JS静态资源
   *
   * @static
   * @return {*}  {void}
   * @memberof JSUtil
   */
  public static loadJS(): void {
    const resourcePath: string[] = [];
    // dom 转pdf
    const jsPDF = (window as any).jspdf?.jsPDF;
    if (!jsPDF) resourcePath.push(resource.dir('assets/js/jspdf/jspdf.js'));
    // pdf 转dom
    const PDF = (window as any).pdfjsLib;
    if (!PDF) resourcePath.push(resource.dir('assets/js/pdf/pdf.js'));
    const html2canvas = (window as any).html2canvas;
    if (!html2canvas) resourcePath.push(resource.dir('assets/js/html2canvas/html2canvas.js'));
    if (!resourcePath.length) return;
    Promise.all(resourcePath.map(path => this.loadScript(path))).catch(error => {
      throw new RuntimeError(
        `加载静态资源失败，请确认JS静态资源是否存在！`,
      );
    });
  }
}